// 在 popup 页面加载时，读取 chrome.storage.local 中存储的数据
window.onload = async function () {
    try {
        const rules = await readFromStorageAsync();
        if (rules) {
            // 格式化 JSON 数据，并显示在页面上
            document.getElementById('rules').value = JSON.stringify(rules, null, 2);
        } else {
            document.getElementById('rules').value = 'No JSON data found in storage.';
        }
    } catch (error) {
        document.getElementById('rules').value = 'Error reading data from storage.';
    }
};

document.addEventListener('DOMContentLoaded', () => {
    console.log('DOMContentLoaded');
});

// 从storeage中读取配置
async function readFromStorageAsync() {
    return new Promise((resolve, reject) => {
        chrome.storage.local.get(['rules'], (result) => {
            if (chrome.runtime.lastError) {
                console.error('Error reading from chrome.storage.local', chrome.runtime.lastError);
                reject(chrome.runtime.lastError);
            } else {
                resolve(result.rules);
            }
        });
    });
}

function onUpload() {
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];

    if (!file) {
        alert('请先选择文件.');
        return;
    }

    // 读取文件内容
    const reader = new FileReader();
    reader.onload = function (event) {
        try {
            const jsonContent = JSON.parse(event.target.result);
            console.log(jsonContent, '文件内容');
            document.getElementById('rules').value = JSON.stringify(jsonContent, null, 2);
            alert('上传成功');
        } catch (e) {
            alert('Invalid JSON file.');
        }
    };
    reader.readAsText(file);
}

document.getElementById('uploadButton').addEventListener('click', onUpload);
document.getElementById('saveButton').addEventListener('click', onSave);

function onSave() {
    const data = document.getElementById('rules').value;
    saveToStorage(JSON.parse(data));
    alert('保存成功');
}

// 将读取到的JSON数据保存到 chrome.storage.local
function saveToStorage(data) {
    chrome.storage.local.set({ rules: data }, () => {
        if (chrome.runtime.lastError) {
            document.getElementById('statusMessage').textContent = 'Error saving data.';
        } else {
            document.getElementById('statusMessage').textContent = 'JSON data successfully saved!';
        }
    });
}

// 导出规则
function exportResult() {
    const data = JSON.parse(document.getElementById('rules').value);

    // 创建一个 Blob 对象来存储 JSON 数据
    const jsonBlob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });

    // 创建下载链接
    const url = URL.createObjectURL(jsonBlob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `rules-${new Date().toLocaleDateString()}.json`; // 设置下载文件的默认名称
    a.click();

    // 释放 Blob URL
    URL.revokeObjectURL(url);
}

// 导出数据为 JSON 文件
document.getElementById('exportButton').addEventListener('click', exportResult);
